﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;

namespace TireService.Web.View.AdminView
{
    public partial class ManageEdiPartners : System.Web.UI.Page
    {

        #region Public Properties

        public int PartnerId
        {
            get
            {
                if (ViewState["_partnerid"] != null)
                    return (int)ViewState["_partnerid"];
                else
                    return 0;
            }
            set
            {
                ViewState["_partnerid"] = value;
            }
        }

        #endregion


        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            if (Page.IsPostBack != true)
            {

            }

            // Bind edi partner data to gridview
            BindEdiPartnerData(db);
            try
            {
                int partnerid = Convert.ToInt32(gvPartnerListEDI.GetRowValues(gvPartnerListEDI.FocusedRowIndex, "PartnerId"));
                BindPartnerSubscriptionPrice(db, partnerid);
            }
            catch (Exception)
            {
                // Nothing - no container selected
            }


            // Change gridview pagesize based on dropdownlist
            gvPartnerListEDI.SettingsPager.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);

            // Dispose connection to database
            db.Dispose();
        }

        /// <summary>
        /// Function that bind edi partner data to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        private void BindEdiPartnerData(TireServiceDB db)
        {
            gvPartnerListEDI.DataSource = db.GetPartnerListEDI();
            gvPartnerListEDI.DataBind();
        }

        /// <summary>
        /// Function that bind partner subscription prices to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="PartnerId">Id on partner</param>
        private void BindPartnerSubscriptionPrice(TireServiceDB db, int PartnerId)
        {
            // Bind to gridview
            gvPartnerSubscriptionPrice.DataSource = db.GetPartnerSubscriptionPrices(PartnerId);
            gvPartnerSubscriptionPrice.DataBind();

            // Prepare data for editmode of edi partner subscription price
            GridViewDataComboBoxColumn ddlSubscription = gvPartnerSubscriptionPrice.Columns["SubscriptionDescriptionDropDown"] as GridViewDataComboBoxColumn;
            ddlSubscription.PropertiesComboBox.ValueType = typeof(int);
            ddlSubscription.PropertiesComboBox.DataSource = db.GetSubscription();
            ddlSubscription.PropertiesComboBox.TextField = "Description";
            ddlSubscription.PropertiesComboBox.ValueField = "SubscriptionId";
            ddlSubscription.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlSubscription.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;
        }

        #region Private Functions

        /// <summary>
        /// Function that change grouping in order gridview
        /// </summary>
        /// <param name="ViewIndex">Integer setting the grouping mode</param>
        protected void GroupOrderData(int ViewIndex)
        {
            gvPartnerListEDI.ClearSort();
            gvPartnerListEDI.GroupSummary.Clear();
            switch (ViewIndex)
            {
                case 0:
                    // Nothing - clear grouping

                    break;
                case 1:
                    //gvPartnerListEDI.GroupBy(gvPartnerListEDI.Columns["City"]);

                    break;
                //case 2:
                //    gvOrder.GroupBy(gvOrder.Columns["CustomerNumber"]);

                //    break;
                //case 3:
                //    gvOrder.GroupBy(gvOrder.Columns["PhotoDate"]);
                //    gvOrder.GroupBy(gvOrder.Columns["CustomerNumber"]);

                //break;
            }
            gvPartnerListEDI.ExpandAll();
        }

        #endregion

        #region Control Functions

        /// <summary>
        /// Button function for export of gridview
        /// </summary>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (ddlExport.Value == "0")
            {
                gvExport.WritePdfToResponse();
            }

            if (ddlExport.Value == "1")
            {
                gvExport.WriteXlsToResponse();
            }

            if (ddlExport.Value == "2")
            {
                gvExport.WriteCsvToResponse();
            }

            if (ddlExport.Value == "3")
            {
                gvExport.WriteRtfToResponse();
            }
        }

        /// <summary>
        /// Dropdown list function that change gridview grouping when selected item is changed
        /// </summary>
        protected void ddlView_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Group data
            GroupOrderData(Convert.ToInt32(ddlView.SelectedValue));
        }

        #endregion

        #region GridView Functions

        ///// <summary>
        ///// Gridview function that change field data for unbound fields
        ///// </summary>
        //protected void gvPartnerListEDI_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        //{
        //    // Format UnBoundColumn UsedCapacity: Show used capacity
        //    if (e.Column.FieldName == "UsedCapacity")
        //    {
        //        // Get containerid
        //        int containerid = Convert.ToInt32(e.GetListSourceFieldValue("ContainerId"));

        //        TireServiceDB db = new TireServiceDB();

        //        // Change field value
        //        e.Value = db.GetContainerUsedCapacity(containerid).First().UsedCapacity.ToString();

        //        db.Dispose();
        //    }

        //    // Format UnBoundColumn FreeCapacity: Show free capacity
        //    if (e.Column.FieldName == "FreeCapacity")
        //    {
        //        // Get containerid
        //        int containerid = Convert.ToInt32(e.GetListSourceFieldValue("ContainerId"));

        //        TireServiceDB db = new TireServiceDB();

        //        // Change field value
        //        e.Value = db.GetContainerFreeCapacity(containerid).First().FreeCapacity.ToString();

        //        db.Dispose();
        //    }
        //}

        /// <summary>
        /// Gridview function for creating edi partner
        /// </summary>
        protected void gvPartnerListEDI_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            // Reset id
            this.PartnerId = 0;

            PartnerListEDI EdiPartner = new PartnerListEDI();

            EdiPartner.Name = Convert.ToString(e.NewValues["Name"]);
            EdiPartner.XMLInterfaceFileName = Convert.ToString(e.NewValues["XMLInterfaceFileName"]);
            if (e.NewValues["CustomerId"] != null)
            {
                EdiPartner.CustomerId = Convert.ToInt32(e.NewValues["CustomerId"]);    
            }
            EdiPartner.ActAsParentCustomer = Convert.ToBoolean(e.NewValues["ActAsParentCustomer"]);
            EdiPartner.ParentPayInvoice = Convert.ToBoolean(e.NewValues["ParentPayInvoice"]);
            EdiPartner.IsCompany = Convert.ToBoolean(e.NewValues["IsCompany"]);
            EdiPartner.SyncToEconomic = Convert.ToBoolean(e.NewValues["SyncToEconomic"]);
            EdiPartner.ManualInvoicing = Convert.ToBoolean(e.NewValues["ManualInvoicing"]);
            EdiPartner.InvoicePBS = Convert.ToBoolean(e.NewValues["InvoicePBS"]);
            EdiPartner.InActive = Convert.ToBoolean(e.NewValues["InActive"]);
            EdiPartner.ServerLink = Convert.ToString(e.NewValues["ServerLink"]);
            EdiPartner.Username = Convert.ToString(e.NewValues["Username"]);
            EdiPartner.Password = Convert.ToString(e.NewValues["Password"]);
            EdiPartner.Port = Convert.ToInt32(e.NewValues["Port"]);

            db.AddPartnerListEDI(EdiPartner);

            // Commit changes to database
            db.SubmitChanges();

            // End edit mode
            e.Cancel = true;
            gvPartnerListEDI.CancelEdit();

            // Reset edit mode
            this.PartnerId = 0;

            // Refresh gridview
            BindEdiPartnerData(db);

            // Close db connection
            db.Dispose();
        }

        /// <summary>
        /// Gridview function for updating edi partner
        /// </summary>
        protected void gvPartnerListEDI_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            // Get id
            this.PartnerId = Convert.ToInt32(e.Keys["PartnerId"]);

            TireServiceDB db = new TireServiceDB();

            PartnerListEDI EdiPartner = new PartnerListEDI();

            // Fecth existing edi partner
            EdiPartner = db.GetPartnerEDI(this.PartnerId);

            if (EdiPartner != null)
            {
                EdiPartner.Name = Convert.ToString(e.NewValues["Name"]);
                EdiPartner.XMLInterfaceFileName = Convert.ToString(e.NewValues["XMLInterfaceFileName"]);
                if (e.NewValues["CustomerId"] != null)
                {
                    EdiPartner.CustomerId = Convert.ToInt32(e.NewValues["CustomerId"]);
                }
                EdiPartner.ActAsParentCustomer = Convert.ToBoolean(e.NewValues["ActAsParentCustomer"]);
                EdiPartner.ParentPayInvoice = Convert.ToBoolean(e.NewValues["ParentPayInvoice"]);
                EdiPartner.IsCompany = Convert.ToBoolean(e.NewValues["IsCompany"]);
                EdiPartner.SyncToEconomic = Convert.ToBoolean(e.NewValues["SyncToEconomic"]);
                EdiPartner.ManualInvoicing = Convert.ToBoolean(e.NewValues["ManualInvoicing"]);
                EdiPartner.InvoicePBS = Convert.ToBoolean(e.NewValues["InvoicePBS"]);
                EdiPartner.InActive = Convert.ToBoolean(e.NewValues["InActive"]);
                EdiPartner.ServerLink = Convert.ToString(e.NewValues["ServerLink"]);
                EdiPartner.Username = Convert.ToString(e.NewValues["Username"]);
                EdiPartner.Password = Convert.ToString(e.NewValues["Password"]);
                EdiPartner.Port = Convert.ToInt32(e.NewValues["Port"]);
            }
            else
            {
                // Edi partner does not exists
                throw new ArgumentException("EDI Partner eksistere ikke");
            }

            // Commit changes to database
            db.SubmitChanges();

            // End edit mode
            e.Cancel = true;
            gvPartnerListEDI.CancelEdit();

            // Reset edit mode
            this.PartnerId = 0;

            // Refresh gridview
            BindEdiPartnerData(db);

            // Close db connection
            db.Dispose();
        }

        protected void gvPartnerSubscriptionPrice_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();
            try
            {
                int partnerid = Convert.ToInt32(gvPartnerListEDI.GetRowValues(gvPartnerListEDI.FocusedRowIndex, "PartnerId"));
                BindPartnerSubscriptionPrice(db, partnerid);
            }
            catch (Exception)
            {
                // Nothing - no container selected
            }

        }

        /// <summary>
        /// Gridview function that change field data for unbound fields
        /// </summary>
        protected void gvPartnerSubscriptionPrice_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        {
            // Format UnBoundColumn SubscriptionDescription: Show description for subscription
            if (e.Column.FieldName == "SubscriptionDescription")
            {
                // Get subscription id
                int subscriptionid = Convert.ToInt32(e.GetListSourceFieldValue("SubscriptionId"));

                TireServiceDB db = new TireServiceDB();

                e.Value = db.GetSubscriptionDescription(subscriptionid);
            }
        }

        /// <summary>
        /// Gridview function for creating edi partner subscription price
        /// </summary>
        protected void gvPartnerSubscriptionPrice_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            PartnerSubscriptionPrice price = new PartnerSubscriptionPrice();

            price.PartnerId = Convert.ToInt32(gvPartnerListEDI.GetRowValues(gvPartnerListEDI.FocusedRowIndex, "PartnerId"));
            price.SubscriptionId = Convert.ToInt32(e.NewValues["SubscriptionId"]);
            price.Price = Convert.ToDecimal(e.NewValues["Price"]);

            db.AddPartnerSubscriptionPrice(price);

            // Commit changes to database
            db.SubmitChanges();

            // End edit mode
            e.Cancel = true;
            gvPartnerSubscriptionPrice.CancelEdit();

            // Refresh gridview
            BindPartnerSubscriptionPrice(db, price.PartnerId);

            // Close db connection
            db.Dispose();
        }

        /// <summary>
        /// Gridview function for updating partner subscription price
        /// </summary>
        protected void gvPartnerSubscriptionPrice_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            // Get id
            int subscriptionid_old = Convert.ToInt32(e.Keys["SubscriptionId"]);
            int partnerid = Convert.ToInt32(gvPartnerListEDI.GetRowValues(gvPartnerListEDI.FocusedRowIndex, "PartnerId"));

            TireServiceDB db = new TireServiceDB();

            PartnerSubscriptionPrice price = new PartnerSubscriptionPrice();

            price = db.GetPartnerSubscriptionPrice(partnerid, subscriptionid_old);
            price.SubscriptionId = Convert.ToInt32(e.NewValues["SubscriptionId"]);
            price.Price = Convert.ToDecimal(e.NewValues["Price"]);

            // Commit changes to database
            db.SubmitChanges();

            // End edit mode
            e.Cancel = true;
            gvPartnerSubscriptionPrice.CancelEdit();

            // Refresh gridview
            BindPartnerSubscriptionPrice(db, price.PartnerId);

            // Close db connection
            db.Dispose();
        }

        #endregion
    }
}